package com.woniu51.k15demo.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu51.k15demo.result.CommonResult;
import com.woniu51.k15demo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

/**
 * @author 杨光
 * @date 2022年02月17日 11:02
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String jwttoken = request.getHeader("jwttoken");
        Map<String, Object> jwt = JwtUtil.parseJWT(jwttoken);

        //放行预检请求
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }

        if(jwt!=null){
            String requestURI = request.getRequestURI();
            Integer userIdint = (Integer)jwt.get("userId");
            Long userId=Long.valueOf(""+userIdint.intValue());
            Set urls = redisTemplate.opsForSet().members("urlPermissions_" + userId);
            Boolean check = urls.contains(requestURI);

            //如果是登录请求，那么放行

            if(!check){
                System.out.println("没权限！！！！！");
                response.setContentType("application/json;charset=utf8");
                CommonResult<Void> result = new CommonResult<>(100102,"没权限",null);
                ObjectMapper mapper = new ObjectMapper();
                response.getWriter().write(mapper.writeValueAsString(result));
            }else {
                request.setAttribute("userId",jwt.get("userId"));
                return true;
            }

        }else{
            System.out.println("未登录！！！！！");
            response.setContentType("application/json;charset=utf8");
            CommonResult<Void> result = new CommonResult<>(100101,"请登录",null);
            ObjectMapper mapper = new ObjectMapper();
            response.getWriter().write(mapper.writeValueAsString(result));
        }
        return false;
    }
}
